<template>
  <div class="wrap" v-loading="loading">
    <h3>{{ $t('picking.Picking Demand Table') }}：{{ picking.pickingNo }}</h3>
    <div class="header">
      <div class="left">
        <span style="font-weight: bold">{{ $t('picking.Required products') }}：</span>
      </div>
      <div class="right">
        <template v-if="picking.pickingLogisticsType === 2">
          <LogisticsPickingButton
            :pickingType="'all'"
            :pickingOrderData="picking"
            :integratedLogisticsSettingData="integratedLogisticsSettingData"
            :defaultLogisticsType="defaultLogisticsType"
            :pickingLogisticsType="picking.pickingLogisticsType"
            @changeOrder="changeOrder"
            style="display: inline"
            class="mgr10"
          ></LogisticsPickingButton>
        </template>
        <template v-else>
          <el-button
            :type="picking.status === 1 ? 'success' : 'danger'"
            :disabled="shippingBtnDisable"
            v-if="this.picking.canShipping || isTesting()"
            :loading="shippingPDFLoading || this.picking.pdfStatus === 1"
            @click="printPickShipping"
          >
            {{ shippingBtn }}
          </el-button>
        </template>

        <el-button type="primary" :loading="printLoading" @click="showDialog">{{ $t('common.export') }}</el-button>
      </div>
    </div>
    <div class="content">
      <el-table :data="data" row-key="id" border :row-class-name="tableRowClassName" :span-method="mergeCells">
        <el-table-column prop="inventoryLocation" align="center" :label="$t('table.inventoryLocation.存放库位')" min-width="160">
          <template slot-scope="{ row }">
            <template v-if="row.inventoryLocationStr === ''">-</template>
            <template v-else>
              {{ row.inventoryLocationStr }}
            </template>
            <template v-if="data.status === 0 && data.type === 2">
              <disposition-inventory-location-info :suitId="row.suitId" :type="2" @change="$router.go(0)"></disposition-inventory-location-info>
            </template>
          </template>
        </el-table-column>

        <el-table-column prop="goodsImage" :label="$t('table.productCover')" align="center" width="110">
          <template slot-scope="{ row }">
            <div class="img-box img-one">
              <img :src="row.goodsImage" alt="" />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="orderId" :label="$t('table.orderId')" align="center" width="170"></el-table-column>
        <el-table-column prop="variationSku" label="SKU" align="center" min-width="300" show-overflow-tooltip>
          <template slot-scope="{ row }">
            {{ row.sku || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="userAccount" :label="$t('table.user name')" align="center" min-width="170"></el-table-column>
        <el-table-column prop="num" :label="$t('common.num')" align="center" width="100"></el-table-column>
        <el-table-column prop="pickingLogisticsTypeStr" :label="$t('table.type')" align="center" width="100"></el-table-column>
        <el-table-column prop="tracking_number" :label="$t('common.物流单号')" align="center" width="210" :show-overflow-tooltip="true">
          <template slot-scope="{ row }">
            <template v-if="row.tracking_number === ''&&row.logisticsErrorMsg === ''">-</template>
            <template v-else-if="row.logisticsErrorMsg === ''&&row.tracking_number != ''">{{ row.tracking_number_type }}-{{ row.tracking_number }} </template>
            <template v-else><p style="color: red;">生成失败：{{row.logisticsErrorMsg}}</p></template>
          </template>
        </el-table-column>
        <el-table-column prop="stickerStatus" :label="getMDName()" align="center" width="150">
          <template slot-scope="{ row }">
            <template v-if="picking.pickingLogisticsType === 2">
              {{ row.tracking_number !== '' ? $t('picking.Picked') : $t('picking.Goods to be picked') }}
            </template>
            <template v-else>
              {{ row.stickerStatus ? (row.isScan ? $t('picking.Picked') : '/') : $t('picking.Goods to be picked') }}
            </template>
          </template>
        </el-table-column>
        <template v-if="picking.pickingLogisticsType === 2">
          <el-table-column prop="num" :label="$t('table.operate')" align="center" min-width="250">
            <template slot-scope="{ row }">
              <LogisticsPickingButton
                :pickingType="'single'"
                :pickingOrderData="row"
                :integratedLogisticsSettingData="integratedLogisticsSettingData"
                :defaultLogisticsType="defaultLogisticsType"
                :pickingLogisticsType="picking.pickingLogisticsType"
                @changeOrder="changeOrder"
                style="display: inline"
              ></LogisticsPickingButton>

              <sticker-custom-button :order="row.formatOrderData" style="display: inline" class="mgl10" @changeOrder="changeOrder"></sticker-custom-button>
            </template>
          </el-table-column>
        </template>
        <el-table-column prop="original_sheet" :label="$t('common.原始面单')" align="center" width="210">
          <template #header>
            <span>{{ $t('common.原始面单') }}</span>
            <el-tooltip class="item" effect="dark" placement="top">
              <template #content>{{ $t('common.原始面单是指未经系统裁切的，由平台直接提供的（平台）面单') }}</template>
              <i class="el-icon-question" style="color: #409eff; margin-left: 5px"></i>
            </el-tooltip>
          </template>
          <template slot-scope="{ row }">
            <el-button v-if="row.downShipping" type="info" @click="printOriginalSheet(row)" :loading="originalSheetLoading">{{ $t('common.下载') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="footer">
      <el-button @click="back">{{ $t('common.back') }}</el-button>
    </div>

    <el-dialog :title="$t('picking.exportTitle')" :visible.sync="PDFDialog" width="400px">
      <div style="margin-top: -15px">
        <el-radio v-model="PDFType" :label="1" class="mgb10">{{ $t('picking.exportRadio1') }}</el-radio>
        <br />
        <el-radio v-model="PDFType" :label="2">{{ $t('picking.exportRadio2') }}</el-radio>
      </div>
      <div slot="footer" class="dialog-footer" style="margin-top: -15px">
        <el-button @click="PDFDialog = false">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="batchPickPDF" :loading="printLoading">{{ $t('common.confirm') }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="$t('picking.pickingFailTitle1')" :visible.sync="failDialog" width="600px" :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false">
      <div style="margin-top: -15px">
        <span v-html="$t('picking.pickingFailText1')"></span>
      </div>
      <div class="mgt10">
        <el-table :data="failOrders" border>
          <el-table-column prop="goodsImage" :label="$t('table.productCover')" align="center" width="110">
            <template slot-scope="{ row }">
              <div class="img-box img-one">
                <img :src="row.goodsImage" alt="" />
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="orderId" :label="$t('table.orderId')" align="center" width="150">
            <template slot-scope="{ row }">
              {{ row.orderId }}
            </template>
          </el-table-column>
          <el-table-column prop="sku" label="SKU" align="center" min-width="120">
            <template slot-scope="{ row }">
              {{ row.sku || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="userAccount" :label="$t('table.user name')" align="center" min-width="120"></el-table-column>
        </el-table>
      </div>
      <div class="mgt20">
        <el-button type="primary" @click="knowFailTips">{{ $t('common.confirm') }}</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="$t('picking.pickingFailTitle2')"
      :visible.sync="allFailDialog"
      width="600px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <div style="margin-top: -15px">
        <span>
          {{ $t('picking.pickingFailText2') }}
        </span>
      </div>
      <div class="mgt20">
        <el-button type="primary" @click="jumpOrder">{{ $t('picking.returnOrderList') }}</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="$t('picking.正在生成面单中,请耐心等待')"
      :visible.sync="lableDialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      width="60%"
    >
      <el-container>
        <el-header>
          <div class="left">
            <el-alert type="error" :closable="false">{{ $t('picking.所有包裹面单生成完毕后即可一键全部下载，您也可以单独下载已生成状态包裹的面单') }}</el-alert>
          </div>
          <div class="right" style="float: right;margin-top: 10px;" >
          <LogisticsPickingButton
            :is-button-all-disabled="picking.status == 1 ? false :true"
            :pickingType="'all'"
            :pickingOrderData="picking"
            :integratedLogisticsSettingData="integratedLogisticsSettingData"
            :defaultLogisticsType="defaultLogisticsType"
            :pickingLogisticsType="picking.pickingLogisticsType"
            @changeOrder="changeOrder"
            @closeLableDialogVisible="closeLableDialogVisible"
            style="display: inline"
            class="mgr10"
          ></LogisticsPickingButton>
          </div>
        </el-header>
        <el-main>
          <el-table :data="data" border style="width: 100%;margin-top: 10px;">
            <el-table-column prop="orderId" :label="$t('table.orderId')" align="center" width="170"></el-table-column>
            <el-table-column prop="tracking_number" :label="$t('picking.物流商')" align="center" width="210">
              <template slot-scope="{ row }">
                <template v-if="row.tracking_number === ''">-</template>
                <template v-else>{{ row.tracking_number_type }}</template>
              </template>
            </el-table-column>

            <el-table-column prop="tracking_number" :label="$t('common.物流单号')" align="center" width="210" :show-overflow-tooltip="true">
             <template slot-scope="{ row }">
               <template v-if="row.tracking_number === ''&&row.logisticsErrorMsg === ''">-</template>
               <template v-else-if="row.logisticsErrorMsg === ''&&row.tracking_number != ''">{{ row.tracking_number_type }}-{{ row.tracking_number }} </template>
               <template v-else><p style="color: red;">生成失败：{{row.logisticsErrorMsg}}</p></template>
             </template>
            </el-table-column>
            <el-table-column prop="stickerStatus" :label="$t('picking.状态')" align="center" width="150">
              <template slot-scope="{ row }">
                <template v-if="picking.pickingLogisticsType === 2" >
                  <template v-if="row.tracking_number===''&&row.logisticsErrorMsg!= ''">
                     生成失败
                  </template>
                  <template v-else>
                     <i class="el-icon-loading" style="color:blue" v-if="row.tracking_number===''"></i>
                    {{ row.tracking_number !== '' ? $t('picking.已生成') :$t('picking.生成中') }}
                  </template>
                </template>
                <template v-else>
                  {{ row.stickerStatus ? (row.isScan ? $t('picking.Picked') : '/') : $t('picking.Goods to be picked') }}
                </template>
              </template>
            </el-table-column>
            <template v-if="picking.pickingLogisticsType === 2">
              <el-table-column prop="num" :label="$t('table.operate')" align="center" min-width="250">
                <template slot-scope="{ row }">
                  <LogisticsPickingButton
                    :is-button-disabled="row.tracking_number !== '' ? false :true"
                    :pickingType="'single'"
                    :pickingOrderData="row"
                    :integratedLogisticsSettingData="integratedLogisticsSettingData"
                    :defaultLogisticsType="defaultLogisticsType"
                    :pickingLogisticsType="picking.pickingLogisticsType"
                    style="display: inline;"
                  ></LogisticsPickingButton>
                </template>
              </el-table-column>
            </template>

          </el-table>
        </el-main>
      </el-container>
    </el-dialog>
  </div>
</template>

<script>
import { batchPickPDF, getPickingInfo, getPickingInfoExcel, printPickShipping, savePickingOrder, surePicking, printOriginalSheet } from '@/api/picking';
import ExportButton from '@/views/order/components/ExportButton.vue';
import { isTesting } from '@/utils/common';
import request from '@/utils/request';
import { getMDAppVersion, getMDName } from '@/utils';
import DispositionInventoryLocationInfo from '@/views/stock/components/DispositionInventoryLocationInfo.vue';
import LogisticsPickingButton from '@/views/order/components/LogisticsPickingButton.vue';
import StickerCustomButton from '@/views/order/components/StickerCustomButton.vue';

export default {
  name: 'packInfo',
  components: {
    DispositionInventoryLocationInfo,
    LogisticsPickingButton,
    StickerCustomButton
  },
  data() {
    return {
      data: [],
      lableDialogVisible: false,
      loading: false,
      pickingNo: '',
      picking: {
        id: '',
        pickingNo: '',
        status: '',
        pdfStatus: 0,
        currentNum: 0,
        totalNum: 0,
        canShipping: false,
        isKnowFail: 0, // 是否知道失败
        failStatus: 0, // 0没有失败 1部分失败 2全失败了
        pickingLogisticsType: 1
      },
      failOrders: [],
      btnLoading: false,
      batchLoading: false,
      PDFDialog: false,
      printLoading: false,
      PDFType: 1,
      shippingPDFLoading: false,
      interval: null,
      failDialog: false, //
      allFailDialog: false, //
      originalSheetLoading: false,

      integratedLogisticsSettingData: [],
      defaultLogisticsType: '',
      logisticsErrorMsgArr: []
    };
  },
  created() {
    this.pickingNo = this.$route.query.pickingNo;
    this.getData();
  },
  computed: {
    shippingBtn() {
      let btnString = this.$t('picking.data exception');
      switch (this.picking.pdfStatus) {
        case 0:
          btnString = this.$t('picking.To be downloaded');
          break;
        case 1:
          btnString = `${this.$t('picking.Downloading')} ${this.picking.currentNum}/${this.picking.totalNum}`;
          break;
        case 2:
          btnString = this.$t('order.downloadShipping');
          break;
      }
      return btnString;
    },
    shippingBtnDisable() {
      return this.picking.pdfStatus !== 2;
    }
  },
  beforeDestroy() {
    if (this.interval) {
      clearInterval(this.interval);
    }
  },
  methods: {
    getMDName,
    getMDAppVersion,
    isTesting,
    getPickingInfoExcel,
    getData() {
      this.loading = true;
      getPickingInfo(this.pickingNo).then((res) => {
        this.loading = false;
        this.picking.id = res.data.id;
        this.picking.pickingNo = res.data.pickingNo;
        this.picking.status = res.data.status;
        this.picking.pdfStatus = res.data.pdfStatus;
        this.picking.currentNum = res.data.currentNum;
        this.picking.totalNum = res.data.totalNum;
        this.picking.canShipping = res.data.canShipping;
        this.picking.isKnowFail = res.data.isKnowFail;
        this.picking.failStatus = res.data.failStatus;
        this.picking.pickingLogisticsType = res.data.pickingLogisticsType;
        this.defaultLogisticsType = res.info.defaultLogisticsType;
        this.integratedLogisticsSettingData = res.info.integratedLogisticsSettingData;
        this.logisticsErrorMsgArr = res.info.logisticsErrorMsgArr;

        // var errorMessage = '';

        // for (var i = 0; i < this.logisticsErrorMsgArr.length; i++) {
        //   errorMessage += this.logisticsErrorMsgArr[i];

        //   // 如果不是数组的最后一个元素，则添加 <br> 标签
        //   if (i < this.logisticsErrorMsgArr.length - 1) {
        //     errorMessage += '<br>';
        //   }
        // }

        // if (errorMessage !== '') {
        //   let str = errorMessage;
        //   let reg = /[;；]/g;
        //   str = str.replace(reg, ' <br/> ');
        //   this.$message({
        //     dangerouslyUseHTMLString: true,
        //     message: str,
        //     duration: 0,
        //     offset: 70,
        //     showClose: true,
        //     type: 'error'
        //   });
        // }

        this.data = res.info.data;
        if (this.picking.pdfStatus !== 2 && this.picking.pickingLogisticsType === 1) {
          this.loopGetData();
        }
        if (this.picking.isKnowFail === 0 && this.picking.failStatus === 1) {
          this.failDialog = true;
        }
        if (this.picking.failStatus === 2) {
          this.allFailDialog = true;
        }

        this.failOrders = res.info.failOrders;
      });
    },
    closeLableDialogVisible(){
      this.lableDialogVisible=false
    },
    loopGetData() {
      this.interval = setInterval(() => {
        getPickingInfo(this.pickingNo).then((res) => {
          this.picking.pdfStatus = res.data.pdfStatus;
          this.picking.currentNum = res.data.currentNum;
          this.picking.totalNum = res.data.totalNum;
          if (this.picking.pdfStatus === 2) {
            clearInterval(this.interval);
            this.getData();
          }
        });
      }, 1000);
    },
    //循环查询订单的物流状态
    lableDialog() {
      this.lableDialogVisible = true;

      this.loopGetLableData();
    },
    //请求包裹下载面单
    loopGetLableData() {
      this.getData();
      this.interval = setInterval(() => {
       getPickingInfo(this.pickingNo).then((res) => {
          //订单状态为1时跳转
          if (this.picking.status==1) {
            this.printPickShipping()
            this.lableDialogVisible=false;
             clearInterval(this.interval);
            return;
          }
          if(this.picking.failStatus==1){
             this.lableDialogVisible=false;
             clearInterval(this.interval);
          }

         this.picking.id = res.data.id;
         this.picking.pickingNo = res.data.pickingNo;
         this.picking.status = res.data.status;
         this.picking.pdfStatus = res.data.pdfStatus;
         this.picking.currentNum = res.data.currentNum;
         this.picking.totalNum = res.data.totalNum;
         this.picking.canShipping = res.data.canShipping;
         this.picking.isKnowFail = res.data.isKnowFail;
         this.picking.failStatus = res.data.failStatus;
         this.picking.pickingLogisticsType = res.data.pickingLogisticsType;
         this.defaultLogisticsType = res.info.defaultLogisticsType;
         this.integratedLogisticsSettingData = res.info.integratedLogisticsSettingData;
         this.logisticsErrorMsgArr = res.info.logisticsErrorMsgArr;
         this.data = res.info.data;
         this.failOrders = res.info.failOrders;

       });
      }, 6000);
    },

    savePicking() {
      const postData = {
        data: []
      };
      this.data.forEach((item) => {
        postData.data.push({
          id: item.id,
          isExcept: item.isExcept
        });
      });
      this.btnLoading = true;
      savePickingOrder(postData).then((res) => {
        this.btnLoading = false;
        this.$successMessage('保存成功');
        this.getData();
        this.$store.dispatch('user/getInfo');
      });
    },
    submitForm() {
      this.$alert(
        `<p>当前拣货单中的所有商品<span style="color: #FF0000">（不包含异常）</span>已完成拣货？</p>` + `<p>如果未完成拣货，请使用「保存」功能保留本次记录</p>`,
        '确认拣货？',
        {
          dangerouslyUseHTMLString: true,
          // type:'warning',
          showCancelButton: true
        }
      )
        .then((res) => {
          const postData = {
            pickingNo: this.pickingNo,
            data: []
          };
          this.data.forEach((item) => {
            postData.data.push({
              id: item.id,
              isExcept: item.isExcept
            });
          });

          surePicking(postData).then((res) => {
            this.$successMessage(res.message);
            this.getData();
            this.$store.dispatch('user/getInfo');
          });
        })
        .catch((res) => {});
    },
    tableRowClassName({ row, rowIndex }) {
      if (row.isExcept === 1) {
        return 'table-is-except-row';
      }
    },
    back() {
      this.$router.push({
        name: 'packList'
      });
    },
    showDialog() {
      this.PDFDialog = true;
    },
    batchPickPDF() {
      this.printLoading = true;
      const postData = {
        pickIds: [this.picking.id],
        PDFType: this.PDFType
      };
      batchPickPDF(postData).then((res) => {
        this.printLoading = false;
        if (res.type === 'application/json') {
          this.$errorMessage('系统繁忙，请稍后再试');
          // this.$errorMessage('功能开发中...');
          return;
        }
        this.PDFDialog = false;
        const pdfFile = window.URL.createObjectURL(new Blob([res.data], { type: 'application/pdf' }));
        // 跳转页面预览
        window.open(pdfFile);
        // 60秒后释放
        setTimeout(() => {
          URL.revokeObjectURL(pdfFile); //释放URL对象
        }, 60000);
      });
    },
    // 打印拣货单的面单
    printPickShipping() {
      this.shippingPDFLoading = true;
      printPickShipping(this.pickingNo).then((res) => {
        this.shippingPDFLoading = false;

        if (res.type === 'application/json') {
          this.$errorMessage('系统繁忙，请稍后再试');
          console.log(res);
          let reader = new FileReader(); // 创建读取文件对象
          reader.readAsText(res, 'utf-8'); // 设置读取的数据以及返回的数据类型为utf-8
          reader.addEventListener('loadend', function () {
            //
            let res = JSON.parse(reader.result); // 返回的数据
          });
          return;
        }

        const pdfFile = window.URL.createObjectURL(new Blob([res.data], { type: 'application/pdf' }));
        // 跳转页面预览
        window.open(pdfFile);
        // 60秒后释放
        setTimeout(() => {
          URL.revokeObjectURL(pdfFile); //释放URL对象
        }, 60000);

        // 刷新数据
        this.$store.dispatch('user/getInfo');

        this.getData();
      });
    },
    // 返回订单列表
    jumpOrder() {
      this.$router.push({
        name: 'orderList'
      });
    },
    // 知道失败了
    knowFailTips() {
      request({
        url: '/picking/knowFail/' + this.picking.id,
        method: 'patch'
      }).then((res) => {
        console.log(res);
      });
      this.failDialog = false;
    },

    mergeCells({ row, column, rowIndex, columnIndex }) {
      const mergeCell = this.mergeCell1();
      if (mergeCell[column.property]) {
        if (mergeCell[column.property][rowIndex]) {
          return [mergeCell[column.property][rowIndex], 1];
        } else {
          // 如果为0则为需要合并的行
          return [0, 0];
        }
      }
    },
    mergeCell1() {
      const mergeObj = {};

      const mergeFieldArr = ['inventoryLocation'];

      mergeFieldArr.forEach((key) => {
        mergeObj[key] = [1];
      });

      let mergeFieldKey = 0;
      this.data.forEach((item, index) => {
        // 第一列数据不处理
        if (index === 0) {
          return;
        }

        if (item.inventoryLocation && item.inventoryLocation === this.data[index - 1].inventoryLocation) {
          mergeFieldArr.forEach((key) => {
            mergeObj[key][mergeFieldKey] += 1;
            mergeObj[key].push(0); // 添加一个0 站位
          });
        } else {
          mergeFieldKey = index; // 记录当前行
          mergeFieldArr.forEach((key) => {
            mergeObj[key].push(1); // 添加一个1
          });
        }
      });

      return mergeObj;
    },

    changeOrder() {
       this.lableDialogVisible=false
      this.$router.go(0); // 刷新当前页面
    },

    printOriginalSheet(row) {
      this.originalSheetLoading = true;
      const postData = {
        downShipping: row.downShipping,
        orderId: row.orderId,
        accountType: row.accountType,
        accountTypeNum: row.accountTypeNum
      };
      printOriginalSheet(postData).then((res) => {
        this.originalSheetLoading = false;

        if (res.type === 'application/json') {
          this.$errorMessage('系统繁忙，请稍后再试');
          console.log(res);
          let reader = new FileReader(); // 创建读取文件对象
          reader.readAsText(res, 'utf-8'); // 设置读取的数据以及返回的数据类型为utf-8
          reader.addEventListener('loadend', function () {
            //
            let res = JSON.parse(reader.result); // 返回的数据
          });
          return;
        }

        const pdfFile = window.URL.createObjectURL(new Blob([res.data], { type: 'application/pdf' }));
        // 跳转页面预览
        window.open(pdfFile);
        // 60秒后释放
        setTimeout(() => {
          URL.revokeObjectURL(pdfFile); //释放URL对象
        }, 60000);

        // // 刷新数据
        // this.$store.dispatch('user/getInfo');
        //
        // this.getData()
      });
    }
  }
};
</script>

<style>
.el-table .table-is-except-row {
  background-color: #ffe6e6 !important;
}
.el-table .table-is-except-row > td {
  background-color: #ffe6e6 !important;
}
</style>

<style scoped lang="scss">
.wrap {
  padding: 30px 30px;

  .header {
    display: flex;
    justify-content: space-between;
  }

  .content {
    padding: 0 0 0;
    margin-top: 20px;
    .tips {
      font-size: 12px;
    }
  }
  .footer {
    margin-top: 30px;
  }
}
.fail-order-card {
  padding-left: 20px;
  height: 100px;
  border: 1px solid #cccccc;
  border-radius: 3px;
  .goods-img {
  }
}
</style>
